<template>
  <div class="user-list-container">
    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ pagination.total }}</div>
            <div class="stat-label">总用户数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ activeUserCount }}</div>
            <div class="stat-label">正常用户</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ adminUserCount }}</div>
            <div class="stat-label">管理员</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ selectedUsers.length }}</div>
            <div class="stat-label">已选择</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form :model="searchForm" inline>
            <el-form-item label="用户名">
              <el-input
                  v-model="searchForm.username"
                  placeholder="请输入用户名"
                  clearable style="width: 200px"
                  @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="账户类型">
              <el-select
                  v-model="searchForm.accountType"
                  placeholder="请选择账户类型"
                  clearable style="width: 120px"
              >
                <el-option
                    v-for="(text, value) in ACCOUNT_TYPE_TEXT"
                    :key="value"
                    :label="text"
                    :value="Number(value)"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                  v-model="searchForm.status"
                  placeholder="请选择状态"
                  clearable style="width: 120px"
              >
                <el-option
                    v-for="(text, value) in USER_STATUS_TEXT"
                    :key="value"
                    :label="text"
                    :value="Number(value)"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon>
                  <Search/>
                </el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon>
                  <Refresh/>
                </el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 15px;">
        <el-col :span="24">
          <el-button type="primary" @click="handleAdd">
            <el-icon>
              <Plus/>
            </el-icon>
            新增用户
          </el-button>
          <el-button type="primary" @click="handleBatchAdd">
            <el-icon>
              <Plus/>
            </el-icon>
            批量创建用户
          </el-button>
          <el-button type="primary" @click="handleBatchResetPwd">
            <el-icon>
              <Plus/>
            </el-icon>
            批量重置密码
          </el-button>
          <el-button
              type="danger"
              :disabled="selectedUsers.length === 0"
              @click="handleBatchDelete"
          >
            <el-icon>
              <Delete/>
            </el-icon>
            批量删除 ({{ selectedUsers.length }})
          </el-button>
        </el-col>
      </el-row>
    </div>


    <!-- 用户表格 -->
    <div class="table-section">
      <el-table
          ref="tableRef"
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
          stripe
          border
          style="width: 100%"
          empty-text="暂无用户数据"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="ID" width="80" sortable/>
        <el-table-column prop="username" label="用户名" min-width="120"/>
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="phone" label="手机号" min-width="130"/>
        <el-table-column prop="accountType" label="账户类型" width="100">
          <template #default="{ row }">
            <el-tag :type="ACCOUNT_TYPE_TAG_TYPE[row.accountType]">
              {{ ACCOUNT_TYPE_TEXT[row.accountType] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="USER_STATUS_TAG_TYPE[row.status]">
              {{ USER_STATUS_TEXT[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable/>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
                title="确定要删除这个用户吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                    type="danger"
                    size="small"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[5, 10, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户对话框 -->
    <UserDialog
        v-model:visible="dialogVisible"
        :user-data="currentUser"
        :is-edit="isEdit"
        @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Search, Refresh, Plus, Delete} from '@element-plus/icons-vue'
import {userApi} from '../api/user'
import UserDialog from '../components/UserDialog.vue'
import {
  ACCOUNT_TYPE_TEXT,
  USER_STATUS_TEXT,
  ACCOUNT_TYPE_TAG_TYPE,
  USER_STATUS_TAG_TYPE,
  ACCOUNT_TYPE,
  USER_STATUS
} from '../utils/constants'

// 响应式数据
const loading = ref(false)
const userList = ref([])
const selectedUsers = ref([])
const tableRef = ref()

const dialogVisible = ref(false)
const currentUser = ref({})
const isEdit = ref(false)

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const searchForm = reactive({
  username: '',
  accountType: null,
  status: null
})

// 计算属性
const activeUserCount = computed(() => {
  return userList.value.filter(user => user.status === USER_STATUS.ACTIVE).length
})

const adminUserCount = computed(() => {
  return userList.value.filter(user => user.accountType === ACCOUNT_TYPE.ADMIN).length
})

// 获取用户列表
const getUserList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      size: pagination.size,
      ...searchForm
    }

    const data = await userApi.getUserList(params)
    userList.value = data.list || response.list || []
    pagination.total = data.total || 0

  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getUserList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    accountType: null,
    status: null
  })
  pagination.current = 1
  getUserList()
}

// 新增用户
const handleAdd = () => {
  currentUser.value = {}
  isEdit.value = false
  dialogVisible.value = true
}

// 批量新增用户
const handleBatchAdd = async () => {
  try {
    await userApi.batchCreateUser(10)
    ElMessage.success('创建成功')
    getUserList()

  } catch (error) {
    console.error('创建用户失败:', error)
  }
}

// 批量重置密码
const handleBatchResetPwd = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要重置的用户')
    return
  }
  try {
    await ElMessageBox.confirm(
        `确定要重置选中的 ${selectedUsers.value.length} 个用户的密码吗？此操作不可恢复！`,
        '批量重置密码确认',
        {
          confirmButtonText: '确定重置',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
    )

    const ids = selectedUsers.value.map(user => user.id)
    const data = await userApi.batchResetPwd(ids)
    ElMessage.success(data)
    getUserList()

  } catch (error) {
    console.error('重置密码失败:', error)
  }
}

// 编辑用户
const handleEdit = (row) => {
  currentUser.value = {...row}
  isEdit.value = true
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await userApi.deleteUser(row.id)
    ElMessage.success('删除成功')
    getUserList()
  } catch (error) {
    console.error('删除用户失败:', error)
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可恢复！`,
        '批量删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
    )

    const ids = selectedUsers.value.map(user => user.id)
    const data = await userApi.batchDeleteUsers(ids)
    // ElMessage.success(`成功删除 ${selectedUsers.value.length} 个用户`)
    ElMessage.success(data)
    getUserList()

  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  console.log('selection:', selection)
  selectedUsers.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  getUserList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.current = current
  getUserList()
}

// 对话框成功回调
const handleDialogSuccess = () => {
  getUserList()
}

// 组件挂载时获取数据
onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.user-list-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.page-header h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.text-right {
  text-align: right;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-section .el-col {
    margin-bottom: 10px;
  }

  .text-right {
    text-align: left;
  }

  .el-table {
    font-size: 12px;
  }

  .stats-section .el-col {
    margin-bottom: 10px;
  }
}
</style>
